//
//  ViewController.m
//  CZeH_Test
//
//  Created by CeriNo on 16/1/18.
//  Copyright © 2016年 AppCan. All rights reserved.
//

#import "ViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@property (nonatomic,assign)BOOL webViewHasLoaded;
@property (nonatomic,strong)UIImageView *transView;
@end

@implementation ViewController


- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor cyanColor];
    //add button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 100, 200, 50);
    [button setTitle:@"test" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(onButtonClick:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:button];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(appCanRootWebViewDidFinishLoading) name:kAppCanRootWebViewDidFinishLoading object:nil];
    
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)appCanRootWebViewDidFinishLoading{
    //网页加载完成之后再把过度图层fade掉
    [UIView animateWithDuration:0.5 animations:^{
        self.transView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.transView removeFromSuperview];
        self.transView = nil;
    }];

    
}

- (void)onButtonClick:(id)sender{
    AppDelegate *APP =(AppDelegate *)[UIApplication sharedApplication].delegate;
    //ace_rootViewController被present进来之后，首次加载WebView需要时间
    //因此present之后还需要一个自定义转场动画过渡
    //这里只是举个栗子，用fade，正式使用时最好和正常present的动画一致
    if (!self.webViewHasLoaded) {
        //截个屏盖上去，网页加载完了再fade
        UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, 0);
        [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        CGImageRef imageRef = viewImage.CGImage;
        UIImage *screenImage = [[UIImage alloc] initWithCGImage:imageRef];
        UIImageView *transView = [[UIImageView alloc]initWithImage:screenImage];
        CGRect frame = APP.ace_startView.frame;
        transView.frame = frame;
        [APP.ace_startView addSubview:transView];
        self.transView = transView;
    }
    
    //用自定义转场动画的时候，present的动画就不要了
    [self presentViewController:APP.ace_rootViewController animated:self.webViewHasLoaded completion:^{
        //5秒钟后自动关闭
        //关闭操作应该由网页端调用自定义的插件完成，目前还没有，所以先这样模拟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        });
    }];
    self.webViewHasLoaded = YES;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
